<?php
namespace App\Repositories;

use App\Models\Msg;
use App\Models\Enlist;
use App\Models\Member;
use App\Models\Superpick;
use App\Models\ElectPoolElected;
use App\Models\ElectPoolJoin;
use App\Models\Activity;
use App\Models\ActivityFill;
use App\Models\ActivityElected;
use Exception;

class MsgRepository
{
    //获取会员的系统目录
    public function getPages(array $filter = [], int $pageSize = 10, int $pageNum=1)
    {
        // sql();
        $res =  Msg::query()
            ->where("df_uid", "=", $filter["wechat_admin_id"])
            ->where("status", "=", 1)
            /*
            ->when(empty($filter['uid']), function($query) use ($filter){
                return $query->where("uid", ">", 0);
            })
            */
            ->groupBy("uid")
            ->groupBy("object_type")
            ->orderBy('id','desc')
            ->paginate($filter['limit']?$filter['limit']:$pageSize, "*", null, $pageNum)
            ->toArray();

        // exit();
        if($pageNum == 1){
            $sys_msg = Msg::whereNull("df_uid")
                            ->where("uid", "=", $filter["wechat_admin_id"])
                            ->orderBy("id", "desc")
                            ->first();
            $sys_msg = isset($sys_msg)?$sys_msg->toArray():"";
            if($sys_msg){
                array_unshift($res['data'], $sys_msg);
            }
        }
        $res = filterPaginateData($res);

        foreach ($res['items'] as $k => $v) {

            $v['unread'] = Msg::where([
                "uid" => $v['uid'],
                "df_uid" => $v['df_uid'],
                'is_read' => 0
            ])->count("id");

            $v['df_uid'] && $v['df_member'] = Member::where("id", "=", $v['df_uid'])->first(["id", "username","avatar"]);

            $res['items'][$k] = $v;
        }

        return $res;
    }

    /**
     * 获取详细列表
     * @Author   thomashtao               bosslen
     * @DateTime 2022-04-11T13:12:16+0800
     * @param    string                   $value  [description]
     */
    public function getList(array $filter = [], int $pageSize = 10, int $pageNum=1)
    {
        $res =  Msg::query()
        ->where("df_uid", "=", $filter["wechat_admin_id"])
        ->where("status", "=", 1)
        ->when(!empty($filter['type']),function($query) use ($filter){
            if(is_array($filter['type'])){
                return $query->whereIn("type", $filter['type']);
            }else{
                return $query->where('type', "=", $filter['type']);
            }
        })
        ->where(function($query) use ($filter){
            $send_uid = intval($filter['send_uid']);
            if($send_uid == -1){
                return $query->whereNotNull("uid");
            }
            if(intval($filter['uid'])){
                return $query->where("uid","=",intval($filter['uid']));
            }else{
                return $query->whereNull("uid")->orWhere("uid", "=", 0);
            }
        })
        ->when(!empty($filter['original']), function($query) use ($filter){
            return $query->where("from", "!=", 1);
        })
        // ->where("from", "!=", 1)
        ->whereNull("deleted_at")
        ->orderBy('create_time','desc')
        ->paginate($pageSize, "*", null, $pageNum)
        ->toArray();

        $res = filterPaginateData($res);

        foreach ($res['items'] as $k => $v) {
            if($v['uid']){
                $v['send_member'] = Member::where("id","=", $v['uid'])->first(["id","username", "avatar","cancel"]);
            }
            if($v['is_read'] == 0){
               Msg::where("id","=",$v['id'])->update(['is_read' => 1, 'read_time' => date("Y-m-d H:i:s")]);
            }
            $res['items'][$k] = $v;
        }
        return $res;
    }

    /**
     * 获取未读数据
     * @Author   thomashtao               bosslen
     * @DateTime 2022-04-11T16:10:08+0800
     * @param    [type]                   $uid    [description]
     * @return   [type]                           [description]
     */
    public function getUnreadAmount($uid)
    {
        if(!intval($uid)) return 0;
        return Msg::where([
            'df_uid' => $uid,
            'is_read' => 0,
            'status' => 1
        ])->count("id");
    }
// 686436
    public function getInfo($id )
    {
        $rs = Msg::where("id","=", $id)->first();
        if(empty($rs)) return NULL;

        switch ($rs['object_type']) {
            case 'enlist':
                $rs['enlist'] = Enlist::where("id","=", $rs['object_id'])->first();
                $rs['link'] = "enlist/member?id=" . $rs['uid'] . '&enlist_id=' . $rs['object_id'];
                break;
            case 'superpick':
                $rs['superpick'] = Superpick::where("id", "=", $rs['object_id'])->first();
                if(empty($rs['superpick']))
                    return $rs;

                $elect_elected = ElectPoolElected::where([
                                    'elect_pool_id' => $rs['superpick']['elect_pool_id'],
                                    'status' => 0
                                ])
                                ->whereRaw("((elect_uid=" . $rs['superpick']['elect_uid'] . ' and elected_uid=' . $rs['superpick']['elected_uid'] . ") or (elect_uid = " . $rs['superpick']['elected_uid'] . ' and  elected_uid=' . $rs['superpick']['elect_uid'] . ") )" )->first();

                $join_id = ElectPoolJoin::where([
                    'elect_pool_id' => $rs['superpick']['elect_pool_id'],
                    'uid' => $elect_elected['elected_uid'] == UID ? $elect_elected['elect_uid'] : $elect_elected['elected_uid'],
                ])->value("id");

                $join_id && $rs['link'] = "elect-pool-join/member?eid=" . $rs['superpick']['elect_pool_id'] . '&ejid=' . $join_id;
                break;

            case 'elect_pool_elected':
                $elect_pool_id = ElectPoolElected::where("id","=", $rs['object_id'])->value("elect_pool_id");
                $join_id = ElectPoolJoin::where([
                    'elect_pool_id' => $elect_pool_id,
                    'uid' => $rs['uid'],
                ])->value("id");
                $join_id && $rs['link'] = "elect-pool-join/member?eid=" . $elect_pool_id . '&ejid=' . $join_id;
                break;

            case 'elect_pool':
                $join_id = ElectPoolJoin::where([
                    'elect_pool_id' => $rs['object_id'],
                    'uid' => $rs['uid'],
                ])->value("id");

                $join_id && $rs['link'] = "elect-pool-join/member?eid=" . $rs['object_id'] . '&ejid=' . $join_id;
                break;
            case 'activity_fill'://活动移入心动区
                $activity_id = ActivityFill::where("id","=", $rs['object_id'])->value("activity_id");
                $activity_id && $rs['link'] = "activity-fill/member?actId=" . $activity_id . "&afId=" . $rs['object_id'];
                break;
            case 'activity'://成功报名活动
                $rs['activity'] = Activity::where("id","=", $rs['object_id'])->first([
                    'id','title','thumb','start_time','end_time','f_join_amount','m_join_amount',"address"
                ]);
                $rs['object_id'] && $rs['link'] = "activity/detail?actId=".$rs['object_id'];
                break;
            case 'activity_elect_pool'://互选成功
                $ae = ActivityElected::where("id","=", $rs['object_id'])->first();

                $afId = ActivityFill::where([
                    'activity_id' => $ae['activity_id'],
                    'uid' => $ae['select_uid'] == UID ? $ae['selected_uid']:$ae['select_uid']
                ])->value("id");

                $afId && $rs['link'] = "activity-fill/member?afId=".$afId."&actId=".$ae['activity_id'];
                break;
            case 'invite_new_user'://小程序邀请新用户
                $rs['link'] = "share/content";
                break;
            default:
                break;
        }

        return $rs;
    }
}

